﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using AjaxControlToolkit;
using System.Drawing;

namespace GandA.Web.UI.Controls
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
    ]
    [DefaultProperty("SelectedValue")]
    [ToolboxData("<{0}:DropDownList runat=\"server\"> </{0}:DropDownList>")]
    [ToolboxBitmap(typeof(System.Web.UI.WebControls.DropDownList))]
    public class DropDownList : CompositeControl
    {
        private System.Web.UI.WebControls.DropDownList ddlControl;
        private RequiredFieldValidator rfvControl;
        private AjaxControlToolkit.ValidatorCalloutExtender vceControl;
        private AjaxControlToolkit.ListSearchExtender lseControl;
        private static readonly object EventSelectedIndexChanged = new object();
        private ArrayList listItem;

        #region Propiedades
        [Bindable(true)]
        [Category("Behavior")]
        [DefaultValue("")]
        [Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                EnsureChildControls();
                return ddlControl.AutoPostBack;
            }

            set
            {
                EnsureChildControls();
                ddlControl.AutoPostBack = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                EnsureChildControls();
                return ddlControl.Text;
            }

            set
            {
                EnsureChildControls();
                ddlControl.Text = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string SelectedValue
        {
            get
            {
                EnsureChildControls();
                return ddlControl.SelectedValue;
            }

            set
            {
                EnsureChildControls();
                ddlControl.SelectedValue = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public int SelectedIndex
        {
            get
            {
                EnsureChildControls();
                return ddlControl.SelectedIndex;
            }

            set
            {
                EnsureChildControls();
                ddlControl.SelectedIndex = value;
            }
        }

        [Bindable(true)]
        [DefaultValue(null)]
        [Localizable(true)]
        [
        Category("Default"),
        Description("The items collection"),
        PersistenceMode(PersistenceMode.InnerDefaultProperty)
        ]
        public virtual ListItemCollection Items
        {
            get
            {
                EnsureChildControls();
                return ddlControl.Items;
            }
        }

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue("")]
        [Localizable(true)]
        public override Unit Width
        {
            get
            {
                EnsureChildControls();
                return ddlControl.Width;
            }

            set
            {
                EnsureChildControls();
                ddlControl.Width = value;
            }
        }

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue("")]
        [Localizable(true)]
        public override Unit Height
        {
            get
            {
                EnsureChildControls();
                return ddlControl.Height;
            }

            set
            {
                EnsureChildControls();
                ddlControl.Height = value;
            }
        }

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public override string CssClass
        {
            get
            {
                EnsureChildControls();
                return ddlControl.CssClass;
            }

            set
            {
                EnsureChildControls();
                ddlControl.CssClass = value;
            }
        }

        [Bindable(true)]
        [Category("Accessibility")]
        [DefaultValue("")]
        [Localizable(true)]
        public override short TabIndex
        {
            get
            {
                EnsureChildControls();
                return ddlControl.TabIndex;
            }

            set
            {
                EnsureChildControls();
                ddlControl.TabIndex = value;
            }
        }

        [Bindable(true)]
        [Category("Controls")]
        [DefaultValue("")]
        [Localizable(true)]
        public RequiredFieldValidator ControlRequiredFieldValidator
        {
            get
            {
                EnsureChildControls();
                return rfvControl;
            }
        }

        [Bindable(true)]
        [Category("Controls")]
        [DefaultValue("")]
        [Localizable(true)]
        public System.Web.UI.WebControls.DropDownList ControlComboBox
        {
            get
            {
                EnsureChildControls();
                return ddlControl;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool EnabledValidator
        {
            get
            {
                EnsureChildControls();
                return rfvControl.Enabled;
            }
            set
            {
                EnsureChildControls();
                rfvControl.Enabled = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue("")]
        [Localizable(true)]
        public string ErrorMessage
        {
            get
            {
                EnsureChildControls();
                return rfvControl.ErrorMessage;
            }

            set
            {
                EnsureChildControls();
                rfvControl.ErrorMessage = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DataTextField
        {
            get
            {
                EnsureChildControls();
                return ddlControl.DataTextField;
            }
            set
            {
                EnsureChildControls();
                ddlControl.DataTextField = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DataValueField
        {
            get
            {
                EnsureChildControls();
                return ddlControl.DataValueField;
            }
            set
            {
                EnsureChildControls();
                ddlControl.DataValueField = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public object DataSource
        {
            get
            {
                EnsureChildControls();
                return ddlControl.DataSource;
            }
            set
            {
                EnsureChildControls();
                ddlControl.DataSource = value;
            }
        }

        [Bindable(true)]
        [Category("Search")]
        [DefaultValue("")]
        [Localizable(true)]
        public bool EnabledSearch
        {
            get
            {
                EnsureChildControls();
                return lseControl.Enabled;
            }
            set
            {
                EnsureChildControls();
                lseControl.Enabled = value;
            }
        }

        [Bindable(true)]
        [Category("Controls")]
        [DefaultValue("")]
        [Localizable(true)]
        public ListSearchExtender ControlListSearchExtender
        {
            get
            {
                EnsureChildControls();
                return lseControl;
            }
        }
        #endregion

        #region Metodos
        protected override void RecreateChildControls()
        {
            EnsureChildControls();
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();

            ddlControl = new System.Web.UI.WebControls.DropDownList();
            ddlControl.ID = "ddlControl1";
            ddlControl.SelectedIndexChanged += _comboBox_SelectedIndexChanged;

            rfvControl = new RequiredFieldValidator();
            rfvControl.ID = "rfValidator1";
            rfvControl.ControlToValidate = ddlControl.ID;
            rfvControl.Text = "Failed validation.";
            rfvControl.Display = ValidatorDisplay.None;
            rfvControl.SetFocusOnError = true;
            rfvControl.ErrorMessage = "Campo requrido";
            rfvControl.Enabled = false;

            vceControl = new ValidatorCalloutExtender();
            vceControl.ID = "vceControl1";
            vceControl.TargetControlID = rfvControl.ID;
            vceControl.HighlightCssClass = "validatorCalloutHighlight";

            lseControl = new ListSearchExtender();
            lseControl.ID = "lseControl1";
            lseControl.TargetControlID = ddlControl.ID;
            lseControl.IsSorted = true;
            lseControl.PromptCssClass = "ListSearchExtenderPrompt";
            lseControl.PromptText = "Escriba para buscar";
            lseControl.QueryTimeout = 2000;
            lseControl.QueryPattern = ListSearchQueryPattern.Contains;
            lseControl.Enabled = false;

            this.Controls.Add(ddlControl);
            this.Controls.Add(rfvControl);
            this.Controls.Add(vceControl);
            this.Controls.Add(lseControl);
        }

        protected override void OnPreRender(EventArgs e)
        {
            bool linkIncluded = false;
            foreach (Control c in Page.Header.Controls)
            {
                if (c.ID == "StyleControls")
                {
                    linkIncluded = true;
                }
            }
            if (!linkIncluded)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "StyleControls";
                csslink.Attributes.Add("href",
                                       Page.ClientScript.GetWebResourceUrl(this.GetType(), "GandA.Web.UI.Controls.Controls.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            base.OnPreRender(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            AddAttributesToRender(writer);

            writer.AddAttribute(
                HtmlTextWriterAttribute.Cellpadding,
                "0", false);
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            ddlControl.RenderControl(writer);
            rfvControl.RenderControl(writer);
            vceControl.RenderControl(writer);
            writer.RenderEndTag();
            writer.RenderEndTag();

            writer.AddAttribute(
                HtmlTextWriterAttribute.Style,
                "display:none", false);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            lseControl.RenderControl(writer);
            writer.RenderEndTag();

            writer.RenderEndTag();
            writer.RenderEndTag();
        }

        //public override ControlCollection Controls
        //{
        //    get
        //    {
        //        this.EnsureChildControls();
        //        return base.Controls;
        //    }
        //}

        public void DataBind()
        {
            ddlControl.DataBind();
        }

        public void AddItem(ListItem item)
        {
            EnsureChildControls();
            if (ddlControl != null)
                ddlControl.Items.Add(item);
        }

        public void AddItem(string text, string value)
        {
            EnsureChildControls();
            ListItem item = new ListItem(text, value);
            if (ddlControl != null)
                ddlControl.Items.Add(item);
        }

        public void AddRange(ListItem[] items)
        {
            EnsureChildControls();
            if (ddlControl != null)
                ddlControl.Items.AddRange(items);
        }

        public void Remove(ListItem item)
        {
            EnsureChildControls();
            if (ddlControl != null)
                ddlControl.Items.Remove(item);
        }

        public void RemoveAt(int index)
        {
            EnsureChildControls();
            if (ddlControl != null)
                ddlControl.Items.RemoveAt(index);
        }

        // The Chaged event.
        [
        Category("Action"),
        Description("Se dispara cuando un valor de la lista es cambiado")
        ]
        public event EventHandler SelectedIndexChanged
        {
            add
            {
                Events.AddHandler(EventSelectedIndexChanged, value);
            }
            remove
            {
                Events.RemoveHandler(EventSelectedIndexChanged, value);
            }
        }

        // The method that raises the Submit event.
        protected virtual void OnSelectedIndexChanged(EventArgs e)
        {
            EventHandler ChangedHandler =
                (EventHandler)Events[EventSelectedIndexChanged];
            if (ChangedHandler != null)
            {
                ChangedHandler(this, e);
            }
        }

        // Handles the Changed event of the TextBox and raises
        // the TextChanged event.
        private void _comboBox_SelectedIndexChanged(object source, EventArgs e)
        {
            OnSelectedIndexChanged(EventArgs.Empty);
        }

        #endregion
    }
}
